<template>
  <div class="login">
    <div class="login-form">
      <div class="form-title">
        <h2>供应商入驻</h2>
      </div>
      <el-form ref="loginFormRef" :model="applyData" :rules="applyRules" label-position="top">
        <el-form-item label="联系人" prop="contact_name" :required="true">
          <el-input
            ref="contact_name"
            v-model="applyData.contact_name"
            placeholder="请输入联系人姓名"
            name="contact_name"
            size="large"
            class="h-[38px]"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone" :required="true">
          <el-input
            ref="contact_phone"
            v-model="applyData.contact_phone"
            placeholder="请输入联系人手机号"
            name="contact_phone"
            size="large"
            class="h-[38px]"
          />
        </el-form-item>
        <el-form-item label="邮箱地址">
          <el-input
            ref="contact_email"
            v-model="applyData.contact_email"
            placeholder="请输入邮箱地址"
            name="contact_email"
            size="large"
            class="h-[38px]"
          />
        </el-form-item>
        <el-form-item label="公司名称" prop="name" :required="true">
          <el-input
            ref="name"
            v-model="applyData.name"
            placeholder="请输入公司名称"
            name="name"
            size="large"
            class="h-[38px]"
          />
        </el-form-item>
        <el-form-item label="营业执照" prop="name" :required="true">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="file"
            :headers="{ Authorization: accessToken }"
            :before-upload="onBeforeUpload"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :show-file-list="false"
          >
            <img
              v-if="applyData.business_license_url"
              :src="applyData.business_license_url"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人身份证正面" prop="name" :required="true">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="file"
            :headers="{ Authorization: accessToken }"
            :before-upload="onBeforeUpload"
            :on-success="onUploadSuccess2"
            :on-error="onUploadError"
            :show-file-list="false"
          >
            <img v-if="applyData.id_card_1" :src="applyData.id_card_1" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人身份证反面" prop="name" :required="true">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="file"
            :headers="{ Authorization: accessToken }"
            :before-upload="onBeforeUpload"
            :on-success="onUploadSuccess3"
            :on-error="onUploadError"
            :show-file-list="false"
          >
            <img v-if="applyData.id_card_2" :src="applyData.id_card_2" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <div class="flex-x-end w-full py-1">
          <el-link type="primary" href="/login">
            <div class="flex-x-end">
              返回登录
              <el-icon><ArrowRightBold /></el-icon>
            </div>
          </el-link>
        </div>

        <!-- 申请按钮 -->
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="w-full"
          @click.prevent="handleApplySubmit"
        >
          提交申请
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import AuthAPI, { type ApplyData } from "@/api/auth";
import { useI18n } from "vue-i18n";
import type { FormInstance } from "element-plus";
import defaultSettings from "@/settings";
import { ref } from "vue";
import { getToken } from "@/utils/auth";
import FileAPI from "@/api/file";
import { UploadProps } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const accessToken = ref(getToken());
const uploadUrl = ref(FileAPI.uploadUrl);
const { t } = useI18n();
const applyFormRef = ref<FormInstance>();
const loading = ref(false); // 按钮 loading 状态

const applyData = ref<ApplyData>({
  password: "",
  name: "",
  contact_name: "",
  contact_phone: "",
  contact_email: "",
  business_license_url: "",
  id_card_1: "",
  id_card_2: "",
  agent: route.query.id as string,
});

const applyRules = computed(() => {
  return {
    name: [
      {
        required: true,
        trigger: "blur",
        message: "请输入公司名称",
      },
    ],
    contact_name: [
      {
        required: true,
        trigger: "blur",
        message: "请输入联系人姓名",
      },
    ],
    contact_phone: [
      {
        required: true,
        trigger: "blur",
        message: "请输入联系人电话",
      },
    ],
    contact_email: [
      {
        required: true,
        trigger: "blur",
        message: "请输入联系人邮箱",
      },
    ],
    business_license_url: [
      {
        required: true,
        trigger: "blur",
        message: "请上传营业执照",
      },
    ],
    id_card_1: [
      {
        required: true,
        trigger: "blur",
        message: "请上传身份证正面",
      },
    ],
    id_card_2: [
      {
        required: true,
        trigger: "blur",
        message: "请上传身份证反面",
      },
    ],
  };
});

const onBeforeUpload: UploadProps["beforeUpload"] = (file) => {
  if (file.type != "image/jpeg" && file.type != "image/png") {
    ElMessage.error("图片类型仅支持PNG,JPG！");
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过5MB！");
    return false;
  }
  return true;
};

const onUploadSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  ElMessage.success("上传成功");
  applyData.value.business_license_url = response.url;
};
const onUploadSuccess2: UploadProps["onSuccess"] = (response, uploadFile) => {
  ElMessage.success("上传成功");
  applyData.value.id_card_1 = response.url;
};
const onUploadSuccess3: UploadProps["onSuccess"] = (response, uploadFile) => {
  ElMessage.success("上传成功");
  applyData.value.id_card_2 = response.url;
};

const onUploadError: UploadProps["onError"] = (file) => {
  ElMessage.error("上传失败");
  console.log("error==", file);
};
// 随机生成6位数有大小写字母+数字密码
function generateRandomString() {
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
}

function handleApplySubmit() {
  applyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      applyData.value.password = await generateRandomString();
      AuthAPI.supplierApply(applyData.value)
        .then((res) => {})
        .catch((error) => {
          console.log(error);
          loading.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  //background: url("@/assets/images/login-bg.jpg") no-repeat center right;
  background: url("@/assets/images/loginBg.jpeg") no-repeat center center;
  background-size: cover;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 24px;
      font-weight: bold;
      color: #3b82f6;
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    width: 50vw;
    height: 90vh;
    overflow-y: scroll;
    padding: 20px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 460px) {
      width: 100%;
      padding: 20px;
    }

    .form-title {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 0 20px;
      text-align: center;
      line-height: 20px;
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .captcha-img {
      height: 48px;
      cursor: pointer;
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }

    .third-party-login {
      display: flex;
      justify-content: center;
      width: 100%;
      color: var(--el-text-color-secondary);

      *:not(:first-child) {
        margin-left: 20px;
      }

      .icon {
        cursor: pointer;
      }
    }

    .idcard-box {
      display: flex;
      align-items: center;

      .idcard-item {
        margin-right: 40px;
      }
    }
  }

  .login-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10px 0;
    text-align: center;
  }
}

:deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  text-align: center;
}
</style>
